import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Row,
    Col,
    Modal,
    Input,
    Select,
    DatePicker,
    message,
    notification
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select, { TextArea } = Input;
const { Item } = Form;
const { RangePicker } = DatePicker;

interface EditorElemProps extends FormComponentProps {
    dispatch?: Dispatch;
    detailInfo?: any;
    INITINFO?: any;
    editVisible: boolean;
    changeModal: (editVisible: boolean) => void;
    searchInfo: any;
}

@connect(({
    logisCenterChargeList: {
        detailInfo,
    },
    common: { INITINFO },
}: any) => ({
    detailInfo,
    INITINFO,
}))

class EditorElemInfo extends Component<EditorElemProps> {
    handleSubmit = () => {
        const { form: { validateFields } } = this.props;
        const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
        validateFields((errors: any, values: any) => {
            if (errors) return;

            const { start_end_time, ...others } = values;
            if (start_end_time) {
                others.startTime = moment(start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
                others.endTime = moment(start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
            } else {
                others.startTime = '';
                others.endTime = '';
            }

            const { searchInfo: search } = this.props;
            const params = { ...others, search };

            const { detailInfo: { id } } = this.props;
            const { dispatch }: any = this.props;

            if (id) {
                params.id = id;
                dispatch({
                    type: 'logisCenterChargeList/addOrEdit',
                    payload: params,
                });
            }
            // 创建 走批量创建
            else {
                const phoneData = values.phone.split('\n'), { phone, ...oth } = params;
                phoneData.map((item: any) => {
                    const rea_phone = item.replace(/\s+/g, '');
                    if (!reg.test(rea_phone)) {
                        return notification.warning({
                            message: `${rea_phone}`,
                            description: '手机号不符合规则'
                        });
                    }

                    dispatch({
                        type: 'logisCenterChargeList/addOrEdit',
                        payload: { phone: rea_phone, ...oth },
                    });
                })
            }

            const { changeModal } = this.props;
            changeModal(false);
        });
    }

    render() {
        const {
            editVisible,
            changeModal,
            detailInfo,
            form: { getFieldDecorator },
            INITINFO: { gardenList },
        } = this.props;

        if (detailInfo.startTime && detailInfo.endTime) {
            detailInfo.start_end_time = [moment(detailInfo.startTime), moment(detailInfo.endTime)];
        }

        const title = Object.keys(detailInfo).length ? '编辑白名单' : '添加白名单';

        return (
            <Modal
                title={title}
                visible={editVisible}
                destroyOnClose
                width={600}
                onOk={this.handleSubmit}
                onCancel={() => changeModal(false)}
            >
                <Form hideRequiredMark className="tableListForm">
                    <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                        <Col md={20} sm={24}>
                            <Item label="　校园小区" colon={false} className="marginB0Import">
                                {getFieldDecorator('gardenId', {
                                    initialValue: detailInfo.gardenId,
                                    rules: [{ required: true, message: '请选择物流中心' }],
                                })(
                                    <Select
                                        showSearch
                                        placeholder="请选择"
                                        filterOption={(input: any, option: any) => (
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        )}
                                    >
                                        {gardenList.map((item: any) => (
                                            <Option value={item.id} key={item.id}>{item.name}</Option>
                                        ))}
                                    </Select>,
                                )}
                            </Item>
                        </Col>
                        <Col md={20} sm={20} style={{ marginTop: 12 }}>
                            <Item label="　有效时间" colon={false} className="marginB0Import">
                                {getFieldDecorator('start_end_time', {
                                    initialValue: detailInfo.start_end_time,
                                    rules: [{ required: true, message: '请选择有效时间' }],
                                })(
                                    <RangePicker
                                        showTime
                                        placeholder={['开始时间', '截止时间']}
                                        style={{ width: '100%' }}
                                        format="YYYY/MM/DD HH:mm:ss"
                                        ranges={{
                                            今天: [moment().startOf('day'), moment().endOf('day')],
                                            本周: [moment().startOf('week'), moment().endOf('week')],
                                            本月: [moment().startOf('month'), moment().endOf('month')],
                                            上月: [
                                                moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                                                moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                                            ],
                                        }}
                                    />,
                                )}
                            </Item>
                        </Col>
                        <Col md={20} sm={24} style={{ marginTop: 12 }}>
                            <Item label="联系人手机" colon={false} className="marginB0Import">
                                {getFieldDecorator('phone', {
                                    initialValue: detailInfo.phone,
                                    rules: [{ required: true, message: '请输入联系人手机' }],
                                })(
                                    <TextArea autoSize={{
                                        minRows: 10,
                                        maxRows: 20,
                                    }} placeholder={detailInfo.id ? "请输入" : "请输入手机号，如需添加多个，换行输入(回车键)"} />,
                                )}
                            </Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        );
    }
}

export default Form.create<EditorElemProps>()(EditorElemInfo);
